<template>
  <order-details @getPrice="getPrice"/>
  <!-- 合计部分 -->
    <div class="total">
        <div class="total-left">
          {{price}}
        </div>
        <div class="total-right" @click="navigatorToPay"  style="background-color: #38CA73;">
            提交订单
        </div>
        <div class="total-right" @click="cancelPay" style="background-color: #fc5531;">
            取消提交
        </div>
    </div>
</template>

<script setup>
import OrderDetails from "../components/OrderDetails.vue";
import router from "../route/route.js";
import {ref} from "vue";
import {getSessionStorage} from "../common.js";
import {userOrderStore} from "../store/unpaidOrder.js";
import {placeOrderAPI} from "../api/api.js";
const orderStore = userOrderStore()
const price = ref(0)
const shopId = ref(null)
const getPrice = (e)=>{
    shopId.value = e.shopId
    price.value = e.totalPrice
}
function filterObject(obj) {
    const newObj = {};
    for (const key in obj) {
        if (key === "orderId" || key === "shopId" || key === "shopLineItems") {
            if (key === "shopLineItems") {
                newObj[key] = obj[key].map(lineItem => {
                    if (lineItem.quantity !== 0) {
                        return {
                            shopItemId: lineItem.shopItemId,
                            id: lineItem.id,
                            quantity: lineItem.quantity
                        };
                    }
                    return null;
                }).filter(Boolean); // 过滤掉为null的元素
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    return newObj;
}

//创建门店订单并且跳转支付
const navigatorToPay = ()=>{
    const orderShopItemDTO = filterObject(orderStore.orderInfo)
    placeOrderAPI(getSessionStorage("user").token,orderShopItemDTO).then(res=>{
        res.data.code === "200"?router.push({path:`/payment/${res.data.data.id}`}):console.log("创建订单失败")
    }).catch(e=>console.log(e))
}
const cancelPay = ()=>{
    router.replace({path:'/order'})
}
</script>

<style scoped>

/****************** 订单合计部分 ******************/
.total{
    width: 100%;
    height: 14vw;

    position: fixed;
    left: 0;
    bottom: 0;

    display: flex;
}
.total .total-left{
    flex: 2;
    background-color: #505051;
    color: #fff;
    font-size: 4.5vw;
    font-weight: 700;
    user-select: none;

    display: flex;
    justify-content: center;
    align-items: center;
}
.total .total-right{
    flex: 1;
    color: #fff;
    font-size: 4.5vw;
    font-weight: 700;
    user-select: none;
    cursor: pointer;

    display: flex;
    justify-content: center;
    align-items: center;
}
</style>